#include "stdafx.h"
#include"Inventory.h"
#include"RegisterManagement.h"
#include"Card.h"
InventoryInvalid InventoryInvalid::instance;

Inventory::Inventory() :Inventory(6)
{

}

Inventory::Inventory(int size)
{
	size = size <= 0 ? 6 : size;
	size = size > 32 ? 32 : size;
	for (int i = 0; i < size; i++)
		cards.push_back(L"");
}

bool Inventory::IsValid()
{
	return true;
}

int Inventory::InsertCard(std::wstring name_id)
{
	if (!RegisterManagement::instance.GetCard(name_id).IsValid())return -1;
	for (int i = 0; i < cards.size(); i++)
	{
		if (cards[i] == L"")
		{
			cards[i] = name_id;
			return i;
		}
	}
	return -1;
}

int Inventory::ExtractCard(std::wstring name_id, bool simulate)
{
	if (!RegisterManagement::instance.GetCard(name_id).IsValid())return -1;
	for (int i = 0; i < cards.size(); i++)
	{
		if (cards[i] == name_id)
		{
			if (simulate)return i;
			cards[i] = L"";
			return i;
		}
	}
	return -1;
}

int Inventory::GetMaxCapacity()
{
	return cards.size();
}

std::wstring Inventory::GetAt(int loc)
{
	if (loc < 0)return L"";
	if (loc >= cards.size())return L"";
	return cards[loc];
}

bool Inventory::SetAt(int loc, std::wstring name_id)
{
	if (loc < 0)return false;
	if (loc >= cards.size())return false;
	if (!RegisterManagement::instance.GetCard(name_id).IsValid())return false;
	cards[loc] = name_id;
	return true;
}

void Inventory::Read(std::istream & in)
{
	int size = 0;
	SaveHelper::Read(in, size);
	cards.clear();
	for (int i = 0; i < size; i++)cards.push_back(L"");
	for (int i = 0; i < cards.size(); i++)
	{
		SaveHelper::Read(in, size);
		if (size == -1)break;
		SaveHelper::Read(in, cards[size]);
	}

}
void Inventory::Write(std::ostream & out)
{
	int size = cards.size();
	SaveHelper::Write(out, size);
	for (int i = 0; i < cards.size(); i++)
	{
		if (cards[i] != L"")
		{
			SaveHelper::Write(out, i);
			SaveHelper::Write(out, cards[i]);
		}
	}
	size = -1;
	SaveHelper::Write(out, size);
}
